<?php

namespace app\merchant\controller;

use app\admin\model\UserMerchant;
use think\facade\View;
use app\common\services\RedisService;
use app\common\Tools;
use app\Request;

class Login 
{
     /**
     * 登录
     *
     * @return void
     */
    public function index()
    {
        return View::fetch();
    }


    /**
     * 注册
     *
     * @return void
     */
    public function register(){
        return View::fetch();
    }

    /**
     * 注册
     *
     * @return void
     */
    public function merchant_register(Request $request){
           $phone = $request->post('phone', '');
           $redis_service = RedisService::getInstance();
            $lock_key = "api:user_auth_personal:" . $phone;

            try {
                $action_lock = $redis_service->acquireLock($lock_key, 3); // 原子设置+过期时间
                if (!$action_lock) {
                    exception('请勿重复提交');
                }

                $post_data = $request->postMore([
                    ['phone', ''],
                    ['captcha', ''],
                    ['password', ''],
                ]);

                Tools::check($post_data, [
                    'phone' => 'require|mobile|unique:user_merchant,mobile',
                    'captcha' => 'require',
                    'password' => 'require|min:6|max:20',
                ], [
                    'phone.require' => '手机号码不得为空',
                    'phone.mobile' => '手机号码格式不正确',
                    'phone.unique' => '手机号码已被注册',
                    'captcha.require' => '验证码不得为空',
                    'password.require' => '密码不得为空',
                    'password.min' => '密码长度不能少于6位',
                    'password.max' => '密码长度不能超过20位',
                ]);

                $exists = UserMerchant::where('mobile', $post_data['phone'])->find();
                if ($exists && $exists['status'] == 0) {
                    exception('认证正在审核中，请勿重复提交');
                }
                $post_data['password'] = md5(sha1($post_data['password']));
                $post_data['mobile']   = $post_data['phone'];
                UserMerchant::create($post_data);

            } catch (\Exception $e) {
                return app('json')->fail($e->getMessage());

            } finally {
                // 🧹 无论成功与否，释放锁
                $redis_service->releaseLock($lock_key);
            }

            return app('json')->success('提交成功，等待审核');
    }

    /**
     * 发送验证码
     *
     * @return void
     */
    public function send_captcha(){
        $phone = request()->post('phone', '');
        if (empty($phone)) {
            return app('json')->fail('手机号码不得为空');
        }
        if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
            return app('json')->fail('手机号码格式不正确');
        }

        // $captcha = rand(100000, 999999);
        $captcha = 123456; // 测试用，实际应用中请使用随机生成的验证码
        cache('merchant_login_captcha_' . $phone, $captcha, 300); // 缓存5分钟

        // 这里可以调用短信发送服务发送验证码
        // send_sms($phone, '您的验证码是：' . $captcha);

        return app('json')->success('验证码已发送');
    }

    /**
     * 登录
     *
     * @return void
     */
    public function merchant_login(Request $request){
           $phone = $request->post('phone', '');
           $redis_service = RedisService::getInstance();
            $lock_key = "api:user_auth_login:" . $phone;

            try {
                $action_lock = $redis_service->acquireLock($lock_key, 3); // 原子设置+过期时间
                if (!$action_lock) {
                    exception('请勿重复提交');
                }

                $post_data = $request->postMore([
                    ['phone', ''],
                    ['password', ''],
                    ['captcha', ''],
                    ['type', 1],
                ]);

                Tools::check($post_data, [
                    'phone' => 'require|mobile',
                    'type' => 'require|in:1,2',
                ], [
                    'phone.require' => '手机号码不得为空',
                    'phone.mobile' => '手机号码格式不正确',
                    'type.require' => '登录方式不得为空',
                ]);
                $exists = UserMerchant::where('mobile', $post_data['phone'])->where('status',1)->find();
                if (!$exists) {
                    exception('账号或密码错误');
                }
                if($post_data['type'] == 1){
                    //密码登录
                    if(empty($post_data['password'])) {
                        exception('密码不得为空');
                    }
    
                   if($exists['password'] != md5(sha1($post_data['password']))){
                        exception('账号或密码错误');
                    }
                }elseif($post_data['type'] == 2){
                    //验证码登录
                    if(empty($post_data['captcha'])) {
                        exception('验证码不得为空');
                    }
                    $captcha = cache('merchant_login_captcha_' . $post_data['phone']);
                    if (!$captcha || $captcha != $post_data['captcha']) {
                        exception('验证码错误或已过期');
                    }

                }
                session('uid', $exists['id']);
                session('user_info', $exists->toArray());
            } catch (\Exception $e) {
                return app('json')->fail($e->getMessage());

            } finally {
                // 🧹 无论成功与否，释放锁
                $redis_service->releaseLock($lock_key);
            }

            return app('json')->success('登陆成功');
    }


    public function login_out() {
        session('uid', null);
        session('user_info', null);
        return redirect('/merchant/login');
    }
}
